<template>
    <el-dialog title="用户授权" v-model="dialogVisible" :before-close="handleClose" :close-on-click-modal="false" top="10vh"
        width="80%">
        <div class="transfer-container">
            <div class="left">
                <div class="search-form-wrapper">
                    <div class="title">待授权用户</div>
                    <div class="seach_list">
                        <el-input :prefix-icon="Search" placeholder="账号及姓名" v-model="tableLeftSearchForm.query"
                            clearable></el-input>

                        <el-button class="is-plain" plain @click="getLeftTableData()">查询</el-button>
                    </div>
                </div>
                <div class="single-table">
                    <el-table ref="tableLeftRef" v-loading="tableLeftLoading" height="100%" :data="tableLeftData" stripe
                        tooltip-effect="dark" :header-cell-style="headerCellStyle" :border="true">
                        <el-table-column type="selection" width="50" align="center"></el-table-column>
                        <el-table-column prop="username" label="账号" show-overflow-tooltip
                            :formatter="formartEmpty"></el-table-column>
                        <el-table-column prop="realName" label="姓名" show-overflow-tooltip
                            :formatter="formartEmpty"></el-table-column>
                        <el-table-column prop="deptName" label="科室" show-overflow-tooltip
                            :formatter="formartEmpty"></el-table-column>
                    </el-table>
                </div>
            </div>
            <div class="center">
                <el-button type="primary" :icon="ArrowRightBold" @click="leftSubmitClick()"></el-button>
                <el-button type="primary" :icon="ArrowLeftBold" @click="rightSubmitClick()"></el-button>
            </div>
            <div class="right">
                <div class="search-form-wrapper">
                    <div class="title">已授权用户</div>
                    <div class="seach_list">
                        <el-input :prefix-icon="Search" placeholder="账号及姓名" v-model="tableRightSearchForm.query"
                            clearable></el-input>

                        <el-button class="is-plain" plain @click="getRightTableData()">查询</el-button>
                    </div>
                </div>
                <div class="single-table">
                    <el-table ref="tableRightRef" v-loading="tableRightLoading" height="100%" :data="tableRightData"
                        stripe tooltip-effect="dark" :header-cell-style="headerCellStyle" :border="true">
                        <el-table-column type="selection" width="50" align="center"></el-table-column>
                        <el-table-column prop="username" label="账号" show-overflow-tooltip
                            :formatter="formartEmpty"></el-table-column>
                        <el-table-column prop="realName" label="姓名" show-overflow-tooltip
                            :formatter="formartEmpty"></el-table-column>
                        <el-table-column prop="deptName" label="科室" show-overflow-tooltip
                            :formatter="formartEmpty"></el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose()">关闭</el-button>
            <el-button type="primary" :loading="btnLoading" @click="submitClick()">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Search, ArrowRightBold, ArrowLeftBold } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { delNullProperty, uniqueArr } from '@/utils';
import { getRoleByUnauthorizedUsers, getRoleByAuthorizedUsers, roleAuthorizeUsers } from '@/api/sys/roleApi.ts';

const btnLoading = ref(false);
const dialogVisible = ref(false);
const headerCellStyle = {
    background: '#f5f7fa',
    fontWeight: 'bold',
    color: '#303133'
}
const roleId = ref('');
/*************左侧待授权的用户table属性************/
const tableLeftRef = ref();
const tableLeftLoading = ref(false);
const tableLeftData = ref<RoleAuthorizeUserEntity[]>([]);
const tableLeftSearchForm = ref({
    query: '',
})


/*************左侧待授权的用户table方法************/
const getLeftTableData = async () => {
    tableLeftLoading.value = true;
    setTimeout(() => {
        tableLeftLoading.value = false;
    })
    const params = {
        roleId: roleId.value,
        ...delNullProperty(tableLeftSearchForm.value)
    } as SysRoleEntityRequestParams
    const res: apiServerResponse = await getRoleByUnauthorizedUsers(params);
    if (res.code == 200) {
        tableLeftData.value = res.result;
    }
    tableLeftLoading.value = false;
};
/*************右侧已授权的用户table属性************/
const tableRightRef = ref();
const tableRightLoading = ref(false);
const tableRightData = ref<RoleAuthorizeUserEntity[]>([]);
const tableRightSearchForm = ref({
    query: '',
})
/*************右侧已授权的用户table方法************/
const getRightTableData = async () => {
    tableRightLoading.value = true;
    setTimeout(() => {
        tableRightLoading.value = false;
    }, 5000);
    const params = {
        roleId: roleId.value,
        ...delNullProperty(tableRightSearchForm.value)
    } as SysRoleEntityRequestParams
    const res: apiServerResponse = await getRoleByAuthorizedUsers(params);
    if (res.code == 200) {
        tableRightData.value = res.result;
    }
    tableRightLoading.value = false;
};


/*************公共方法************/
const leftSubmitClick = () => {
    const selectRows = tableLeftRef.value.getSelectionRows();
    if (selectRows.length == 0) {
        ElMessage.warning("请选择要授权的用户！");
        return;
    } else {
        const combinedData: any = [...tableRightData.value, ...selectRows];
        tableRightData.value = combinedData;

        tableLeftData.value = tableLeftData.value.filter(item => !selectRows.includes(item));
    }


}
const rightSubmitClick = () => {
    const selectRows = tableRightRef.value.getSelectionRows();
    if (selectRows.length == 0) {
        ElMessage.warning("请选择要取消授权的用户！");
        return;
    } else {
        const combinedData: any = [...tableLeftData.value, ...selectRows];
        tableLeftData.value = combinedData;
        tableRightData.value = tableRightData.value.filter(item => !selectRows.includes(item));
    }

}
const openLoad = (id: string) => {
    dialogVisible.value = true;
    roleId.value = id;
    init()
}
const init = async () => {
    await getLeftTableData();
    await getRightTableData();
}

const submitClick = async () => {
    btnLoading.value = true;
    setTimeout(() => {
        btnLoading.value = false;
    }, 5000);
    try {
        const userIdArr = uniqueArr(tableRightData.value, 'userId');
        const params = {
            roleId: roleId.value,
            userId: userIdArr
        } as RoleAuthorizeUserRequestParams
        const res: apiServerResponse = await roleAuthorizeUsers(params)
        if (res.code == 200 && res.result) {
            ElMessage.success("操作成功！");
            handleClose()
        } else {
            ElMessage.error("操作失败！");
        }
        btnLoading.value = false;

    } catch (error) {
        ElMessage.error("未知错误，请联系管理员！");
    }
    btnLoading.value = false;
}
const handleClose = () => {
    dialogVisible.value = false;
    btnLoading.value = false;
}
const formartEmpty = (row: any, column: any, cellValue: any, index: number) => {
    if (cellValue == null || cellValue == '') {
        return '-'
    }
    return cellValue
}

defineExpose({
    openLoad
})
</script>

<style lang="scss" scoped>
.flex-space {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;

    .el-icon {
        padding-right: 10px;
    }
}

.transfer-container {
    display: flex;
    height: 60vh;

    .left {
        width: 45%;
    }

    .center {
        width: 10%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .right {
        width: 45%;
    }
}
</style>